package com.lottery.im.module.main.ui;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Patterns;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.webkit.URLUtil;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.DefaultWebClient;
import com.lottery.im.MyApplication;
import com.lottery.im.R;
import com.lottery.im.base.BaseActivity;
import com.lottery.im.constant.SpKeyConstant;
import com.lottery.im.util.Density;
import com.lottery.im.util.DeviceHelper;
import com.lottery.im.util.DisplayHelper;
import com.lottery.im.util.SPUtils;
import com.lottery.im.widget.dialog.BottomWebViewMoreDialog;
import com.lottery.im.widget.floatwindow.FloatWindow;
import com.lottery.im.widget.floatwindow.IFloatWindow;
import com.lottery.im.widget.floatwindow.MoveType;
import com.lottery.im.widget.floatwindow.Screen;

/**
 * Created by lianwufeng on 2017/12/15.
 */

public class AgentWebViewActivity extends BaseActivity {

  private final static String URL_KEY = "URL_KEY";
  private final static String TITLE_KEY = "TITLE_KEY";
  private final static String TYPE_KEY = "TYPE_KEY";

  public static void create(Fragment fragment, String url, String title) {
    Intent intent = new Intent(fragment.getActivity(), AgentWebViewActivity.class);
    intent.putExtra(URL_KEY, url);
    intent.putExtra(TITLE_KEY, title);
    fragment.startActivity(intent);
  }

  public static void create(Context context, String url, String title) {
    Intent intent = new Intent(context, AgentWebViewActivity.class);
    intent.putExtra(URL_KEY, url);
    intent.putExtra(TITLE_KEY, title);
    intent.putExtra(TYPE_KEY, 1);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
  }

  @BindView(R.id.tv_title) TextView mTvTitle;
  @BindView(R.id.layout_all) LinearLayout mLayoutAll;

  private String mLoadUrl;
  private String mTitle;
  private int mType;

  private AgentWeb mAgentWeb;

  private final static int WINDOW_REQUEST_CODE = 888;

  private Dialog mDialog;

  @Override protected int getLayoutResId() {
    return R.layout.activity_agent_webview;
  }

  @Override protected void initPresenter() {
    init();
  }

  private void init() {

    mLoadUrl = getIntent().getStringExtra(URL_KEY);
    mTitle = getIntent().getStringExtra(TITLE_KEY);
    mType = getIntent().getIntExtra(TYPE_KEY, 0);

    if (TextUtils.isEmpty(mTitle)) {
      mTvTitle.setText("加载中...");
    } else {
      mTvTitle.setText(mTitle);
    }

    if (!mLoadUrl.startsWith("http://") && !mLoadUrl.startsWith("https://")) {
      mLoadUrl = "http://" + mLoadUrl;
    }

    mAgentWeb = AgentWeb.with(this)
        .setAgentWebParent(mLayoutAll, new LinearLayout.LayoutParams(-1, -1))
        .useDefaultIndicator(ContextCompat.getColor(this, R.color.web_progress))
        .setWebChromeClient(new WebChromeClient() {
          @Override public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
          }
        })
        .setWebViewClient(new WebViewClient() {
          @Override public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            String title = view.getTitle();
            if (!Patterns.WEB_URL.matcher(title).matches() && !URLUtil.isValidUrl(
                title)) {
              mTvTitle.setText(title);
            }
          }

          @Override public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
          }
        })
        .setMainFrameErrorView(R.layout.layout_webview_error, -1)
        .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
        .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK)//打开其他应用时，弹窗咨询用户是否前往其他应用
        .interceptUnkownUrl() //拦截找不到相关页面的Scheme
        .createAgentWeb()
        .ready()
        .go(mLoadUrl).clearWebCache();

    mAgentWeb.getAgentWebSettings().getWebSettings().setSupportZoom(true);
    mAgentWeb.getAgentWebSettings().getWebSettings().setBuiltInZoomControls(true);
    mAgentWeb.getAgentWebSettings().getWebSettings().setDisplayZoomControls(false);
    mAgentWeb.getAgentWebSettings().getWebSettings().setTextZoom(100);

    mAgentWeb.getAgentWebSettings().getWebSettings().setDomStorageEnabled(true);
    mAgentWeb.getAgentWebSettings().getWebSettings().setJavaScriptEnabled(true);
  }

  @OnClick({ R.id.iv_back, R.id.iv_more }) public void onViewClicked(View view) {

    switch (view.getId()) {
      case R.id.iv_back:
        if (mType == 1) {
          openWindow();
        } else {
          finish();
          overridePendingTransition(R.anim.in_from_left, R.anim.out_to_right);
        }
        break;
      case R.id.iv_more:
        if (null != mDialog && mDialog.isShowing()) {
          mDialog.dismiss();
          mDialog = null;
        }

        mDialog = new BottomWebViewMoreDialog().create(this, mType,
            (parent, view1, position, id) -> {
              switch (position) {
                case 0:
                  toXF();
                  break;
                case 1:
                  if (null != mAgentWeb) {
                    mAgentWeb.getWebCreator().getWebView().reload();
                  }
                  break;
                case 2:
                  if (null != mAgentWeb && mAgentWeb.getWebCreator().getWebView().canGoBack()) {
                    mAgentWeb.getWebCreator().getWebView().goBack();
                  } else {
                    finish();
                  }
                  break;
              }
            });
        mDialog.setOnDismissListener(dialog -> {
          if (null != mDialog && mDialog.isShowing()) {
            mDialog.dismiss();
          }
          mDialog = null;
        });
        mDialog.show();
        break;
    }
  }

  private void toXF() {

    if (mType == 1) {
      showToast("已取消浮窗");
      mType = 0;
      return;
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
      if (Settings.canDrawOverlays(this)) {
        // 已获取悬浮窗权限
        openWindow();
      } else {
        // 无悬浮窗权限，提示打开
        showToast("该功能需要打开浮窗权限");

        if (DeviceHelper.isFlyme()) {
          Intent intent = new Intent("com.meizu.safe.security.SHOW_APPSEC");
          intent.setClassName("com.meizu.safe", "com.meizu.safe.security.AppSecActivity");
          intent.putExtra("packageName", getPackageName());
          intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          startActivity(intent);
        } else {
          Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
          intent.setData(Uri.parse("package:" + getPackageName()));
          startActivityForResult(intent, WINDOW_REQUEST_CODE);
        }
      }
    } else {
      openWindow();
    }
  }

  /**
   * 悬浮窗
   * type 0 收到设置浮窗 关闭界面 1 上次保存到浮窗 关闭时候 再次显示
   */
  private void openWindow() {
    SPUtils.put(MyApplication.getInstance(), SpKeyConstant.FLOAT_URL,
        mAgentWeb.getWebCreator().getWebView().getUrl());
    IFloatWindow old = FloatWindow.get("old");
    if (old == null) {
      IFloatWindow cancel2 = FloatWindow.get("cancel2");
      if (cancel2 == null) {
        FloatWindow
            .with(getApplicationContext())
            .setTag("cancel2")
            .setView(R.layout.layout_window)
            .setCancelParam2(320)
            .setMoveType(MoveType.inactive, 0, 0)
            .setDesktopShow(false)
            .build();
      }
      IFloatWindow cancel = FloatWindow.get("cancel");
      if (cancel == null) {
        FloatWindow
            .with(getApplicationContext())
            .setTag("cancel")
            .setView(R.layout.layout_window)
            .setCancelParam2(300)
            .setMoveType(MoveType.inactive, 0, 0)
            .setDesktopShow(false)
            .build();
      }

      ImageView imageView = new ImageView(MyApplication.getInstance());
      imageView.setBackgroundResource(R.drawable.btn_fc);
      FloatWindow
          .with(getApplicationContext())
          .setTag("old")
          .setView(imageView)
          .setMoveType(MoveType.slide, 0, 0)
          .setWidth(DisplayHelper.getScreenWidth(this) / 15)
          .setHeight(DisplayHelper.getScreenWidth(this) / 15)
          //.setFilter(false, AgentWebViewActivity.class)
          .setX(Screen.width, 0.8f)  //设置控件初始位置
          .setY(DisplayHelper.getScreenHeight(this) / 3 * 2)
          .setParentHeight(DisplayHelper.getScreenHeight(this))
          .setMoveStyle(300, new AccelerateInterpolator())
          .setDesktopShow(false)
          .build();
      imageView.setOnClickListener(v -> {
        String url =
            (String) SPUtils.get(MyApplication.getInstance(), SpKeyConstant.FLOAT_URL, "");
        AgentWebViewActivity.create(getApplicationContext(),
            url, "");
        FloatWindow.destroy("old");
        FloatWindow.destroy("cancel");
        FloatWindow.destroy("cancel2");
        FloatWindow.cancel();
      });
      finish();
      overridePendingTransition(R.anim.in_from_left, R.anim.out_to_right);
    } else {
      finish();
      overridePendingTransition(R.anim.in_from_left, R.anim.out_to_right);
    }
  }

  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {

    if (null != mAgentWeb && mAgentWeb.handleKeyEvent(keyCode, event)) {
      return true;
    }
    return super.onKeyDown(keyCode, event);
  }

  @Override
  protected void onPause() {
    if (null != mAgentWeb) {
      mAgentWeb.getWebLifeCycle().onPause();
    }
    super.onPause();
  }

  @Override
  protected void onResume() {
    if (null != mAgentWeb) {
      mAgentWeb.getWebLifeCycle().onResume();
    }
    super.onResume();
  }

  @Override public void onBackPressed() {
    if (mType == 1) {
      openWindow();
    } else {
      super.onBackPressed();
    }
  }

  @Override protected void onDestroy() {

    if (null != mAgentWeb) {
      mAgentWeb.getWebLifeCycle().onDestroy();
    }
    super.onDestroy();
    Density.setCustomDensity(this,MyApplication.getInstance());
  }


}
